<?php


//Converts class number to roman number
function convertToRoman($num)
{
	 $n = intval($num);
    $res = '';
 
    // roman_numerals array
    $roman_numerals = array(
                'M'  => 1000,
                'CM' => 900,
                'D'  => 500,
                'CD' => 400,
                'C'  => 100,
                'XC' => 90,
                'L'  => 50,
                'XL' => 40,
                'X'  => 10,
                'IX' => 9,
                'V'  => 5,
                'IV' => 4,
                'I'  => 1);
 
    foreach ($roman_numerals as $roman => $number) 
    {
        // divide to get  matches
        $matches = intval($n / $number);
 
        // assign the roman char * $matches
        $res .= str_repeat($roman, $matches);
 
        // substract from the number
        $n = $n % $number;
    }
    return $res;
}



//Prints students of selected class
function printStudents($odsutni)
{
		$sql="SELECT * FROM students WHERE class_id={$_GET['classID']} ORDER BY name";
		$result=mysql_query($sql) or die(mysql_error());
		echo("<form name=odsutniForm method=post action=cas.php?classID={$_GET['classID']}&cas={$_GET['cas']}&smena={$_GET['smena']}&subjID={$_GET['subjID']} >");
		while($stud=mysql_fetch_array($result))
		{
			if($odsutni==0)
			{
				echo($stud['name']."<br />");
			}
			else
			{
				echo($stud['name']);
					echo("  <input type=checkbox name=odsutniChb[] value={$stud['student_id']} /><br/>");
					
			}
		}
		if($odsutni==1)
			echo("<input type=submit name=submitOdsutni value=Зачувај />");	
		echo("</form>");
}


//Checks who is the master od selected class
function checkMaster()
{
	$sql="SELECT class_id, class, sub_class FROM class WHERE classMaster={$_SESSION['proff_id']}";
	$result=mysql_query($sql) or die(mysql_error());
	$master=mysql_fetch_array($result);
	echo("<a href=class.php?classID={$master['class_id']}&class={$master['class']}&subCl={$master['sub_class']} >".convertToRoman($master['class'])."-{$master['sub_class']} </a>");
}


//Draw the schedule day
function sceduleDay($den, $cas, $smena)
{
	$sql="SELECT schedule.*, class, sub_class, class.class_id, name, subjects.subject_id FROM schedule, class, subjects WHERE prof_id={$_SESSION['proff_id']} AND cas={$cas} AND den={$den} AND class.class_id=schedule.class_id AND subjects.subject_id=schedule.subject_id AND smena=$smena";
	$result=mysql_query($sql) or die("Can not select the schedule for this proffesor ".mysql_error());
	$sched = mysql_fetch_array($result);
	if($sched['den']=="")
	{
		echo("<td width=200 height=70>&nbsp;</td>");
	}
	else
	{
		echo("<td align=center valign=middle width=200 height=70>{$sched['name']}");
		echo("<br />");
		echo("<a href=cas.php?classID={$sched['class_id']}&cas={$sched['cas']}&smena={$sched['smena']}&subjID={$sched['subject_id']} >".convertToRoman($sched['class'])."-{$sched['sub_class']}</a></td>");	
		global $linkArg;
		$linkArg="classID={$sched['class_id']}&cas={$sched['cas']}&smena={$sched['smena']}&subjID={$sched['subject_id']}";
	}
}


//Draws the table with students where proffesor can give grades to them
function printStundentCasTable()
{
	$sql="SELECT * FROM students WHERE class_id={$_GET['classID']} ORDER BY name";
	$result=mysql_query($sql) or die("Can not select studentts for this class ".mysql_error());
	$broj=1;
	echo <<<TABLE
		<table class="altrowstable" id="alternatecolor" >
			<tr>
				<th>Број</th>
    			<th>Име и презиме</th>
    			<th>Оцнека</th>
    			<th>Забелеша</th>
    			<th>&nbsp;</th>
TABLE;
	while($class=mysql_fetch_array($result))
	{
		echo("<tr>");
		echo("<form  id=ocenkaForm method=post action={$_SERVER['PHP_SELF']}?classID={$_GET['classID']}&cas={$_GET['cas']}&smena={$_GET['smena']}&subjID={$_GET['subjID']} >");
			echo("<td>{$broj}.</td>");
			echo("<td> <a onclick=myPopup2(".$class['student_id'].") href= > {$class['name']} </a> </td>");
			echo <<<OCENKA
			<td>
    				<input type="text" name="ocenka" id="ocenka" />
        			<input type="hidden" name="studID" value="{$class['student_id']}" />
			</td>
OCENKA;
			echo <<<ZABELESKA
			<td>
				<input type="text" name="zabeleska" id="ocenka" />
			</td>
ZABELESKA;
			echo("<td>");
				echo("<input type=submit name=submitOcenka value=Зачувај оценка />");
			echo("</td>");
		echo("</form><tr>");
		$broj++;	
	}
	echo("</table>");
}



//Checks who is apsent and and stores the the result i data base
function checkOdsutni()
{
	$odsutniList=@$_POST['odsutniChb'];
	if(empty($odsutniList))
	{
		echo("NEMA ODSUTNI");	
	}
	else
	{	echo("Odsutni studenti se : ");
		$br=count($odsutniList);
		for($i=0; $i<$br; $i++)
		{
			$sql="SELECT name FROM students WHERE student_id=$odsutniList[$i]";
			$result=$result=mysql_query($sql) or die("Can not select student ".mysql_error());
			$stud=mysql_fetch_array($result);
			
			$sql="SELECT * FROM odsutni WHERE datum=CURDATE() AND student_id=$odsutniList[$i] AND cas={$_GET['cas']}";
			$result=mysql_query($sql) or die("ERROR".mysql_error());
			$count=mysql_num_rows($result);
			if($count==0)
			{			
				$sql2="INSERT INTO odsutni VALUES (NULL, $odsutniList[$i], CURDATE(), {$_GET['cas']}, {$_GET['smena']}, 1, 0, 0)";
				$result2=mysql_query($sql2) or die("ERROR ".mysql_error());
				echo("<font color=#FF0000 >".$stud['name']."</font>, ");
			}
			else
			{
				echo("<br/>Студентоот <b>{$stud['name']}</b> е веќе заверен како одсутен ");	
			}
		}	
	}
	
}



//Zaverka na cas
function zaveriCas()
{
	//$odsutniList=@$_POST['odsutniChb'];
	if(isset($_POST['casSubmit']))
	{
		//Checking if class is laready saved, so profesor can not save the same class twice
		$sql2="SELECT *FROM cas WHERE datum=CURDATE() AND cas={$_GET['cas']} AND smena={$_GET['smena']}";
		$result2=mysql_query($sql2) or die("Can not select information abotut this class".mysql_error());
		$count=mysql_num_rows($result2);
		if($count==0)
		{
			
			$sql="INSERT INTO cas (datum, cas, smena, zabeleska) VALUES (CURDATE(), '{$_GET['cas']}', '{$_GET['smena']}', '{$_POST['zabeleskaC']}' )";
			$result=mysql_query($sql) or die("Can not enter data for cas ".mysql_error());
				echo("<font color=#00FF00 >Часот {$cas['cas_id']} {$br} е успешно заверен</font>");
		}
		else
		{
			echo("<font color=#FF0000 >Часот е веке заверен и не мозе да се завери по втор пат!</font>");
		}
	}
}



//// To protect MySQL injection 
function mySqlInjection($str)
{
	$str = stripslashes($str);
	$str = mysql_real_escape_string($str);
	
	return $str;	
}



//SAVE the grade
function saveGrade()
{
	//If zacuvaj is clicked
		if(isset($_POST['submitOcenka']))
		{
			$currYear=date("Y");
			$currYearP=$currYear+1;
			$currDate=date("Y-m-d");
			$dateStartPrvo="{$currYear}-09-01";
			$dateEndPrvo="{$currYear}-11-13";
			$dateStartVtoro="{$currYearP}-01-15";
			$dateEndVtoro="{$currYearP}-06-15";
			$semester=0;
			if(strtotime($currDate) >= strtotime($dateStartPrvo) && strtotime($currDate) <= strtotime($dateEndPrvo))
			{
				$semester=1;
				$ocenka=mySqlInjection($_POST['ocenka']);
				$zabeleska=mySqlInjection($_POST['zabeleska']);
				$sql="INSERT INTO grades VALUES(NULL, '{$_GET['studID']}', '{$_GET['subjID']}', '{$ocenka}', '{$semester}', '{$zabeleska}')";
				$result=mysql_query($sql) or die("Can not enter values".mysql_error());
			}
			else if(strtotime($currDate) >= strtotime($dateStartVtoro) && strtotime($currDate) <= strtotime($dateEndVtoro))
			{
				$semester=2;
				$ocenka=mySqlInjection($_POST['ocenka']);
				$zabeleska=mySqlInjection($_POST['zabeleska']);
				$sql="INSERT INTO grades VALUES(NULL, {$_GET['studID']}, {$_GET['subjID']}, {$ocenka}, {$semester}, {$zabeleska})";
				$result=mysql_query($sql) or die("Can not enter values".mysql_error());	
			}
			else
			{
				echo("<font color=#FF0000 >Во тек е одмор не може да внесувате оценки</font>");	
			}	
		}
}




//Printing the ediary for master proffesot
function printDnevnik()
{
	//Getting the names of grades in coresponding class
	$sql4="SELECT subjects.* FROM subjects, class, proffclass, profsubject WHERE subjects.subject_id=profsubject.subject_id AND profsubject.proffesor_id=proffclass.proffesor_id AND proffclass.class_id=class.class_id AND class.class_id={$_GET['classID']} ORDER BY name";
	$result4=mysql_query($sql4) or die("Can not select the subjects for coreponding class ".mysql_error());
	echo("<tr>");
		echo("<th>&nbsp;</hd>");
		while($subjName=mysql_fetch_array($result4))
		{
			echo("<th>{$subjName['name']}</th>");
		}
		echo("<th>Изостаноци<br/> Оправдани</th>");
		echo("<th>Изостаноци<br/> Неоправдани</th>");
	echo("</tr>");
	
	
	//Selecting the student of coreponding class
	$sql="SELECT students.* FROM students WHERE students.class_id={$_GET['classID']} ORDER BY name";
	$result=mysql_query($sql) or die("Can not select students of this class ".mysql_error());
		$redBr=1;
		while($stud=mysql_fetch_array($result))
		{
			$linkPom="class.php?studID={$stud['student_id']}&classID={$_GET['classID']}&class={$_GET['class']}&subCl={$_GET['subCl']}";
			
			$sql5="SELECT SUM(izostanoci_vkupno) AS ivk FROM odsutni WHERE student_id={$stud['student_id']}";
			$result5=mysql_query($sql5) or die("ERROR ".mysql_error());
			$izostanok=mysql_fetch_array($result5);
			
			
			echo("<tr align=left valign=top >");
			if($izostanok['ivk'] > 0)
			{
				echo("<td valign=middle align=center><b>".$redBr.". ".$stud['name']."</b><br/><a  onclick=myPopup3({$stud['student_id']}) href= ><font color=#FF0000>има не заверени<br/> изостаноци</font></a></td>");
			}
			else
			{
				echo("<td valign=middle align=center><b>".$redBr.". ".$stud['name']."</b></td>");	
			}
			
			
			//Selecting the grades of this class
			$sql2="SELECT subjects.* FROM subjects, class, proffclass, profsubject WHERE subjects.subject_id=profsubject.subject_id AND profsubject.proffesor_id=proffclass.proffesor_id AND proffclass.class_id=class.class_id AND class.class_id={$_GET['classID']} ORDER BY name";
			$result2=mysql_query($sql2) or die("Can not select the subjects for coreponding class ".mysql_error());
			while($subj=mysql_fetch_array($result2))
			{
				echo("<td><table class=altrowstable id=alternatecolor width=100%>");
				//echo("<br /><font color=#000066 >&nbsp;&nbsp;&nbsp;  ".$subj['name']."</font><br/>");
				//Getting the gaades for this student
				$sql3="SELECT * FROM grades WHERE student_id={$stud['student_id']} AND subject_id={$subj['subject_id']}";
				$result3=mysql_query($sql3) or die("Can not select grades for this student ".mysql_error());
					echo("<tr align=left valign=top>");
						echo("<th>Оценка</th>");
						echo("<th>Опис</th>");
						echo("<th>Пол</th>");
						echo("<th>I</th>");
						echo("<th>II</th>");
						echo("<th>Кон</th>");
					echo("</tr>");
					
					//Selectnig final grades
					$sql7="SELECT * FROM finalgrades WHERE student_id={$stud['student_id']} AND subject_id={$subj['subject_id']}";
					$result7=mysql_query($sql7) or die("Can not selec final grades ".mysql_error());
					$finalG=mysql_fetch_array($result7);
					
					
					$vkupno=mysql_num_rows($result3);
					$br=1;
				while($grade=mysql_fetch_array($result3))
				{
					echo("<tr align=center valign=middle>");
						echo("<td>{$grade['ocenka']}</td>");
						echo("<td>{$grade['description']}</td>");
						echo("<td>{$grade['semester']}</td>");
						if($br==1)
						{
							if($finalG['final_first']==NULL)
							{
								echo("<td rowspan={$vkupno}>&nbsp;</td>");
							}
							else
							{
								echo("<td rowspan={$vkupno}><font color=#FF0000 >{$finalG['final_first']}</font></td>");	
							}
							
							if($finalG['final_second']==NULL)
							{
								echo("<td rowspan={$vkupno}>&nbsp;</td>");
							}
							else
							{
								echo("<td rowspan={$vkupno}><font color=#FF0000 >{$finalG['final_second']}</font></td>");	
							}
							
							if($finalG['final_second']==NULL)
							{
								echo("<td rowspan={$vkupno}>&nbsp;</td>");
							}
							else
							{
								echo("<td rowspan={$vkupno}><font color=#FF0000 ><b>{$finalG['final_grade']}</b></font></td>");	
							}	
						}
					//echo("&nbsp;&nbsp&nbsp;&nbsp&nbsp;".$grade['ocenka']." ".$grade['description']." ".$grade['semester']." || ");
					echo("</tr>");
					$br++;
					
				}
				echo("</table></td>");
			}
				//Selecting izostanoci :)
				$sql6="SELECT SUM(izostanoci_opravdani) AS opr, SUM(izostanoci_neopravdani) AS nopr FROM odsutni WHERE student_id={$stud['student_id']}";
				$result6=mysql_query($sql6) or die("ERROR".mysql_error());
				$odsutni=mysql_fetch_array($result6);
				$count=mysql_num_rows($result6);
				if($odsutni['opr']!=0 && $odsutni['nopr']!=0)
				{
					echo("<td align=center valign=middle><b>{$odsutni['opr']}</b></td>");
					echo("<td align=center valign=middle><b>{$odsutni['nopr']}</b></td>");
				}
				else
				{
					echo("<td align=center valign=middle><b>{$odsutni['opr']}</b></td>");
					echo("<td align=center valign=middle><b>{$odsutni['nopr']}</b></td>");
				}
			echo("</tr>");
			$redBr++;	
			echo("<br/>");
		}	
}





//Prints students in izostanoci.php
function printStudentIzostanok()
{
	echo("<form name=izostVk method=post action={$_SERVER['PHP_SELF']}?studID={$_GET['studID']} >");
	//Selecting the name of the student
	$sql="SELECT * FROM students WHERE student_id={$_GET['studID']}";
	$result=mysql_query($sql) or die("Can not select student ".mysql_error());
	$stud=mysql_fetch_array($result);
	
	$sql="SELECT SUM(izostanoci_vkupno) AS ivk, COUNT(izostanoci_vkupno) AS brVk FROM odsutni WHERE student_id={$stud['student_id']}";
	$result=mysql_query($sql) or die("ERROR ".mysql_error());
	$izosVk=mysql_fetch_array($result);
	$vkupno=$izosVk['brVk']+1;
	if($izosVk['ivk'] > 0)
	{
		echo("<table class=altrowstable id=alternatecolor>");
			echo("<tr align=center>");
				echo("<th rowspan=$vkupno align=center valign=middle>{$stud['name']}</th>");
				echo("<th>Датум</th>");
				echo("<th>Час</th>");
				echo("<th>Предмет</th>");
				echo("<th>Оправдано</th>");
			echo("</tr>");
			
			$sql="SELECT * FROM odsutni WHERE odsutni.student_id={$stud['student_id']} ";
			$result=mysql_query($sql) or die(mysql_error());
			$godina=date("Y");
			while($odsutni=mysql_fetch_array($result))
			{
				$sql1="SELECT name FROM schedule, subjects WHERE smena={$odsutni['smena']} AND cas={$odsutni['cas']} AND godina=$godina";
				$result1=mysql_query($sql1) or die("Can not select the subject name ".mysql_error());
				$subj=mysql_fetch_array($result1);
				
				echo("<tr align=center>");
					echo("<td>{$odsutni['datum']}</td>");
					echo("<td>{$odsutni['cas']}</td>");
					echo("<td>{$subj['name']}</td>");
					echo("<td><input type=checkbox name=opravdaniChb[] value={$odsutni['izostanok_id']} </td>");
				echo("</tr>");
			}
			echo("<tr align=right>");
				echo("<td colspan=5 align=right><input type=submit name=izosSubmit value=Зачувај /></td>");
			echo("</tr>");
			
		echo("</table>");
		echo("</form>");
	}
}



function saveIzostanoci()
{
	if(isset($_POST['izosSubmit']))
	{
		$izostanociList=@$_POST['opravdaniChb'];
		if(empty($izostanociList))
		{
			//print_r($izostanociList);
			$sql="SELECT * FROM odsutni WHERE student_id={$_GET['studID']} AND izostanoci_vkupno=1";
			$result=mysql_query($sql) or die("ERROR ".mysql_error());
			while($neopravdani=mysql_fetch_array($result))
			{
				$sql1="UPDATE odsutni SET izostanoci_vkupno=0, izostanoci_neopravdani=1 WHERE izostanok_id={$neopravdani['izostanok_id']}";
				$result1=mysql_query($sql1);	
			}
			echo("<font color=#009900>Изосаноците се сочувани</font>");
		}
		else
		{
			$br=count($izostanociList);
			for($i=0; $i<$br; $i++)
			{
				//echo($br." ");
				//print_r($izostanociList);
				$sql="UPDATE odsutni SET izostanoci_vkupno=0, izostanoci_opravdani=1 WHERE izostanok_id=$izostanociList[$i]";
				$result=mysql_query($sql);	
			}
			$sql1="SELECT * FROM odsutni WHERE student_id={$_GET['studID']} AND izostanoci_vkupno=1";
			$result1=mysql_query($sql1) or die("ERROR ".mysql_error());
			
			while($neopravdani=mysql_fetch_array($result1))
			{
				$sql3="UPDATE odsutni SET izostanoci_vkupno=0, izostanoci_neopravdani=1 WHERE izostanok_id={$neopravdani['izostanok_id']}";
				$result3=mysql_query($sql3);
			}
			echo("<font color=#009900>Изосаноците се сочувани</font>");
		}
?>
<script language="javascript">
	window.opener.location.href = window.opener.location.href;

  	if (window.opener.progressWindow)
	{
    	window.opener.progressWindow.close()
  	}
  	window.close();
</script>
<?php
		
	}
}
?>